package com.Downloaders;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import com.Animations.AnimUtil;
import com.Managers.DirManagerClass;
import com.Managers.PictureManagerClass;
import com.SoapClasses.SoapUtil;
import com.utils.CircularPictureClass.onCircularCompleted;


public class ProfilePictureDownloader extends AsyncTask<String, Integer, Bitmap> {

    private onProfilePictureDownloaded callbackProfilePicture;

    private View progress;

    private String tag;

    public interface onProfilePictureDownloaded {

        void completed(Bitmap result);
    }

    public onProfilePictureDownloaded getCallbackProfilePicture() {

        return callbackProfilePicture;
    }

    public void setCallbackProfilePicture(onProfilePictureDownloaded callbackProfilePicture) {

        this.callbackProfilePicture = callbackProfilePicture;
    }

    public void setProgress(View progress) {

        this.progress = progress;
    }

    private void downloadImage(String URL, final String SDPATH) {

        if (!URL.startsWith("http")) {
            String n = SoapUtil.UPP + URL;
            URL = n;
        }

        try {
            URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);

            PictureManagerClass.getCircularBitmap(myBitmap, new onCircularCompleted() {

                @Override
                public void Completed(Bitmap circular) {

                    savePicture(circular, SDPATH);
                }
            });

        }
        catch (IOException e) {
            e.printStackTrace();

        }
    }

    private String makeUrl(String iTag) {

        String fullSdPath = "";
        String withOutExt = "";
        //
        String[] sp = iTag.split("/");
        //
        withOutExt = sp[sp.length - 1];
        fullSdPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + DirManagerClass.PictureProfilePath + withOutExt;
        // ///////////////////////////////////////////////////////////////////////
        fullSdPath = fullSdPath.replace(".jpg", ".png");
        return fullSdPath;
    }

    private void savePicture(Bitmap circular, String SDPATH) {

        try {

            Bitmap csave = PictureManagerClass.ImageResize(circular);

            File f = new File(SDPATH);

            FileOutputStream fOut = new FileOutputStream(f);
            csave.compress(CompressFormat.PNG, 0, fOut);
            fOut.flush();
            fOut.close();
            csave.recycle();

            this.onPostExecute(BitmapFactory.decodeFile(SDPATH));
        }
        catch (Exception e) {
            Log.e("ERROR_PROFILEPICDOWNLOADER", e.getMessage());
            e.printStackTrace();
        }

    }

    private Bitmap verifyForFile(String URL, String SDPATH) {

        if (!SDPATH.isEmpty()) {
            File mbmp = new File(SDPATH);

            if (!mbmp.exists()) {

                downloadImage(URL, SDPATH);
            }
            else {
                return BitmapFactory.decodeFile(SDPATH);

            }

        }
        return null;

    }

    /**
     * @param params
     *            Url of the picture to download
     */
    @Override
    protected Bitmap doInBackground(String... params) {

        tag = params[0];

        if (tag == null)
            return null;

        Bitmap toc = verifyForFile(tag, makeUrl(tag));
        return toc;

    }

    @Override
    protected void onPostExecute(Bitmap result) {

        if (result != null) {

            if (progress != null) {
                AnimUtil.animateFadeOut(progress);
            }

        }
        if (callbackProfilePicture != null)
            callbackProfilePicture.completed(result);
    }

}
